﻿using Face8280WebSocketServer.DB.User;
using Face8280WebSocketServer.Interface;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using Face8280WebSocketServer.Utility.RSA;
using Face8280WebSocketServer.Utility.JWT;

namespace Face8280WebSocketServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        #region MyRegion
        private ILogger<AuthenticationController> _logger = null;
        private IJWTService _iJWTService = null;
        private IUserService _user;
        public AuthenticationController(ILoggerFactory factory,
            ILogger<AuthenticationController> logger,
            IUserService user, IJWTService service)
        {
            this._logger = logger;
            this._iJWTService = service;
            this._user = user;
        }
        #endregion

        [Route("Get")]
        [HttpGet]
        public IEnumerable<int> Get()
        {
            return new List<int>() { 1, 2, 3, 4, 6, 7 };
        }

        [Route("GetKey")]
        [HttpGet]
        public string GetKey()
        {
            string keyDir = Directory.GetCurrentDirectory();
            if (RSAHelper.TryGetKeyParameters(keyDir, false, out RSAParameters keyParams) == false)
            {
                keyParams = RSAHelper.GenerateAndSaveKey(keyDir, false);
            }

            return JsonConvert.SerializeObject(keyParams);
        }

        [Route("Login")]
        [HttpPost]
        public string Login(string name, string password)
        {

            {
                //大家自己在开发的时候这里肯定是需要去数据库中验证
            }
            var users = _user.Query<UserDetail>(x => x.UserName == name).ToList();
            if (users.Count != 1)
            {
                return JsonConvert.SerializeObject(new
                {
                    result = false,
                    error = "User not find!"
                });

            }
            var user = users.First();
            if (user.UserName.Equals(name) && user.UserPassword.Equals(password))//应该数据库
            {
                string token = this._iJWTService.GetToken(user);
                return JsonConvert.SerializeObject(new
                {
                    result = true,
                    token
                });
            }
            else
            {
                return JsonConvert.SerializeObject(new
                {
                    result = false,
                    token = "User password error!"
                });
            }
        }
    }
}